package com.cnpc.ds.handler;

import com.cnpc.eisc.base.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * 统一异常处理
 *
 * @author jyq
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    @ResponseBody
    public Result error(HttpRequestMethodNotSupportedException e) {
        log.warn("发生 HttpRequestMethodNotSupportedException 异常,不支持的操作{}", e.getMethod());
        return Result.error("不支持" + e.getMethod() + "操作");
    }

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Result error(HttpServletRequest request, Exception e) {
        log.error("请求url:{},发生 Exception 异常", request.getRequestURL(), e);
        return Result.error();
    }

    @ExceptionHandler(IllegalArgumentException.class)
    @ResponseBody
    public Result error(IllegalArgumentException e) {
        log.info("发生 自定义 IllegalArgumentException 异常 :{}", e);
        return Result.error(e.getMessage());
    }

    @ExceptionHandler(HttpMessageNotReadableException.class)
    @ResponseBody
    public Result error(HttpMessageNotReadableException e) {
        log.info("发生 参数转化错误 HttpMessageNotReadableException 异常 :{}", e);
        return Result.error("参数错误");
    }
}
